package com.xy.xymall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.xy.common.constant.AuthServerConstant;
import com.xy.common.exception.BizCodeEnum;
import com.xy.common.utils.R;
import com.xy.common.vo.MemberRespVo;
import com.xy.xymall.auth.feign.MemberFeignService;
import com.xy.xymall.auth.vo.UserLoginVo;
import com.xy.xymall.auth.vo.UserRegistVo;
import com.xy.xymall.auth.feign.ThirdPartFeignService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author XY
 * @version 1.0.0
 * @ClassName LoginController.java
 * @createTime 2020年10月14日 19:32:00
 * 登录controller层
 */
@Controller
public class LoginController {

    @Autowired
    ThirdPartFeignService thirdPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * @param phone
     * @author XY
     * @date 2020/10/16 15:18
     * @return com.xy.common.utils.R
     * 调用远程接口发送短信验证码
     */
    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone){
        //TODO 1、接口防刷

        String redisCode=redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);
        if(StringUtils.isNotEmpty(redisCode)){
            String[] s = redisCode.split("_");
            long l = Long.parseLong(s[1]);
            //60秒内不能再发
            if(System.currentTimeMillis() - l< 60000 ){
                return R.error(BizCodeEnum.VALID_SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.VALID_SMS_CODE_EXCEPTION.getMessage());
            }
        }
        //加上时间后缀是为了判断是否能够再次发送验证码
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring= code +"_"+System.currentTimeMillis();
        //redis缓存验证码,并要防止同一个phone在60秒内再次发送验证码
        //2、验证码的再次校验，redis  存key要包含手机号，value为code  sms:code:15574958983 -> 123456
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,substring,10, TimeUnit.MINUTES);
        thirdPartFeignService.sendCode(phone, code);
        return R.ok();
    }

    /**
     * @Author XY
     * @Date 2020/10/17 9:29
     * @Param [userVo, result, redirectAttributes]
     * @Return java.lang.String
     * 重定向携带数据，利用session原理。将数据放在session中。只要跳到下一个页面取出这个数据后，session里面的数据就会被删掉
     *  TODO 分布式情况下 session问题
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userVo, BindingResult result, RedirectAttributes redirectAttributes){
        if(result.hasErrors()){
            Map<String, String> collect = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
//            model.addAttribute("errors",collect);
            //重定向携带数据
            redirectAttributes.addFlashAttribute("errors",collect);
            //Request method 'POST' not supported
            //用户注册--》/regist(post)-->转发到reg.html(路径映射默认都是get方式才能访问的)
            //校验出错转发到注册页
            return "redirect:http://auth.xymall.com/reg.html";
        }
        //调用远程服务进行注册
        //1、校验验证码
        String code=userVo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userVo.getPhone());
        if(StringUtils.isNotEmpty(s)){
            if(code.equals( s.split("_")[0])){
                //删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userVo.getPhone());
                //验证码通过,调用远程服务进行注册
                R r = memberFeignService.regist(userVo);
                if(r.getCode()==0){
                    return "redirect:http://auth.xymall.com/login.html";
                }else{
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.xymall.com/reg.html";
                }
            }else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                return "redirect:http://auth.xymall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错转发到注册页
            return "redirect:http://auth.xymall.com/reg.html";
        }
    }


    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute==null){
            return "login";
        }else{
            return "redirect:http://xymall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo loginVo, RedirectAttributes redirectAttributes, HttpSession session){
        //远程登陆
        R r = memberFeignService.login(loginVo);
        if(r.getCode()==0){
            session.setAttribute(AuthServerConstant.LOGIN_USER,r.getData("data",new TypeReference<MemberRespVo>(){}));
            return "redirect:http://xymall.com";
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.xymall.com/login.html";
        }
    }
}
